import axios from 'axios'
import { errorDeal, getStore, successDeal } from '@/utils/utils'
import NProgress from 'nprogress'

axios.interceptors.request.use(
  function (config) {
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  function (response) {
    return response
  },
  function (error) {
    return Promise.reject(error)
  }
)
/**
 *@describe http请求
 *@method {String} 请求方式
 *@url {String} 接口地址
 *@params {Object} 对应接口参数
 **/

export default async function _http(
  method = 'post',
  { url, apiName = '' },
  params = {},
  loading = true,
  headers = {}
) {
  if (loading) {
    NProgress.start()
  }

  //----获取token,Authorization 鉴权信息
  const token = window.localStorage.getItem('USER_TOKEN') || ''
  const uesrInfo = getStore('USER_INFO') || {}
  const Authorization = getStore('USER_AUTHOR') || {
    Authorization: `'','','',3,20,''`,
  }

  let json = {}
  // if (url == '/ums/w/company/login') {
  //   json = {
  //     username: uesrInfo.username || '',
  //   }
  // }
  json = {
    token: token ? `Bearer ${token}` : '',
    username: uesrInfo.username || '',
  }

  return axios({
    method: method,
    url: '' + url,

    headers: Object.assign(
      {
        'Content-Type': 'application/json;charset=UTF-8;',
        platformHeadType: 'rcmsPlatform',
      },
      json,
      Authorization || {},
      headers
    ),
    params: method === 'get' ? params : '',
    data: typeof params === 'object' ? JSON.stringify(params) : params,
    timeout: 1000 * 60 * 2,
    responseType: 'blob' || undefined,
    withCredentials: true,
  })
    .then((res) => {
      if (loading) {
        NProgress.done()
      }
      // 数据流，直接返回
      if (url.indexOf('/eas/import/order/download') != -1) {
        return res
      }
    })
    .catch((error) => {
      if (loading) {
        NProgress.done()
      }
      errorDeal(error, url)
      throw error
    })
}
